package com.joe.rememberanything.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.joe.rememberanything.dao.PMF;
import com.joe.rememberanything.model.Item;

/**
 * the servlet action for handle Item operations
 * @author zhoulonghuan
 * @email zhoulonghuan@gmail.com
 * @modified 090415
 */
@SuppressWarnings("serial")
public class ItemAction extends HttpServlet {
	private static final Logger log = Logger.getLogger(ItemAction.class.getName());
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		doPost(req,resp);
	}
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setCharacterEncoding("UTF-8");
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		String cmd = StringUtils.trimToEmpty(req.getParameter("cmd"));
		System.out.println("cmd:"+cmd);
		//test Item
		if(cmd.equals("test")){
			testJDO();
			return;
		}
		//if you want to publish the app to use it,you should change the email account below with yours
		if(!(user!=null&&user.getEmail().equals("zhoulonghuan@gmail.com"))){
			if(cmd.equals("newItem")||cmd.equals("delete")||cmd.equals("update")){
				resp.getWriter().println("<font color='red'>sorry,please login first.</font>");
				return;
			}
		}
		
		if(cmd.equals("newItem")){
			Item item = new Item();
			String title = StringUtils.trimToEmpty(req.getParameter("title"));
			if(title.equals("")){
				resp.getWriter().println("<font color='red'>you must input the title for a new item.</font>");
				return;
			}
			String content = StringUtils.trimToNull(req.getParameter("content"));
			Date createTime = new Date();
			String labelID = StringUtils.trimToNull(req.getParameter("labelID"));
			String state = StringUtils.trimToNull(req.getParameter("state"));
			if(state==null){
				state = "0";  //default is not done
			}
			String positionStr = StringUtils.trimToEmpty(req.getParameter("position"));
			int position = 0;
			if(!positionStr.equals("")){
				position = Integer.parseInt(positionStr);
			}
			String status = StringUtils.trimToNull(req.getParameter("status"));
			if(status==null){
				status = "1";  //default is public item
			}
			String level = StringUtils.trimToNull(req.getParameter("level"));
			if(level==null){
				level = "3";  //default is 3rd level
			}
			item.setTitle(title);
			item.setContent(content);
			item.setCreateTime(createTime);
			item.setLabelID(labelID);
			item.setState(state);
			item.setPosition(position);
			item.setStatus(status);
			item.setLevel(level);
			PersistenceManager pm = PMF.getPMFactory().getPersistenceManager();
			try{
				pm.makePersistent(item);
				log.info("add a new item at "+new Date().toLocaleString());
			}finally{
				pm.close();
			}
			
		}
		//delete an item
		if(cmd.equals("delete")){
			String id = StringUtils.trimToEmpty(req.getParameter("id"));
			if(id.equals("")){
				resp.getWriter().print("<font color='red'>you must select an item to delete.</font>");
				return;
			}
			String selectQuery = "select from "+Item.class.getName()+" where id=="+id;
			PersistenceManager pm = PMF.getPMFactory().getPersistenceManager();
			List<Item> items = (List<Item>) pm.newQuery(selectQuery).execute();
		    if(!items.isEmpty()){
		    	pm.deletePersistent(items.get(0));
		    }
			pm.close();
		}
		//update an item
		if(cmd.equals("update")){
			Item item = new Item();
			String idStr = StringUtils.trimToEmpty(req.getParameter("id"));
			long id = 0;
			if(idStr.equals("")){
				resp.getWriter().println("<font color='red'>you must got an id to update a new item.</font>");
				return;
			}else{
				id = Long.parseLong(idStr);
			}
			String title = StringUtils.trimToEmpty(req.getParameter("title"));
			if(title.equals("")){
				resp.getWriter().println("<font color='red'>you must input the title for a new item.</font>");
				return;
			}
			String content = StringUtils.trimToNull(req.getParameter("content"));
			Date createTime = new Date();
			String labelID = StringUtils.trimToNull(req.getParameter("labelID"));
			String state = StringUtils.trimToNull(req.getParameter("state"));
			if(state==null){
				state = "0";  //default is not done
			}
			String positionStr = StringUtils.trimToEmpty(req.getParameter("position"));
			int position = 0;
			if(!positionStr.equals("")){
				position = Integer.parseInt(positionStr);
			}
			String status = StringUtils.trimToNull(req.getParameter("status"));
			if(status==null){
				status = "1";  //default is public item
			}
			String level = StringUtils.trimToNull(req.getParameter("level"));
			if(level==null){
				level = "3";  //default is 3rd level
			}
			item.setId(id);
			item.setTitle(title);
			item.setContent(content);
			item.setCreateTime(createTime);
			item.setLabelID(labelID);
			item.setState(state);
			item.setPosition(position);
			item.setStatus(status);
			item.setLevel(level);
			PersistenceManager pm = PMF.getPMFactory().getPersistenceManager();
			try{
				pm.makePersistent(item);
				log.info("add a new item at "+new Date().toLocaleString());
			}finally{
				pm.close();
			}
			
		}
		//select all items for admin,and the others can't see the private items
		String query = "select from " + Item.class.getName() + " order by level desc, createTime desc";
		if(null==user){
			query = "select from " + Item.class.getName() + " where status==\"1\" order by createTime desc";
		}else{
			//resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
			if(!user.getEmail().equals("zhoulonghuan@gmail.com")){  //i'm the admin-_-
				query = "select from " + Item.class.getName() + " where status==\"1\" order by createTime desc";
			}
		}
		PersistenceManager pm = PMF.getPMFactory().getPersistenceManager();
	    List<Item> items = (List<Item>) pm.newQuery(query).execute();
	    List<Item> myItems = new ArrayList<Item>();
	    for(Item i:items){
	    	myItems.add(i);
	    }
	    req.setAttribute("items", myItems);
	    pm.close();
		try {
			req.getRequestDispatcher("ListIndex.jsp").forward(req, resp);
		} catch (ServletException e) {
			e.printStackTrace();
			log.info(e.toString());
		}
	}
	public void testJDO(){
		Item item = new Item();
		item.setTitle("i'm title");
		item.setContent("i'm content");
		item.setCreateTime(new Date());
		item.setLabelID(null);
		item.setState("0");
		item.setPosition(0);
		item.setStatus("1");
		item.setLevel("3");
		
		PersistenceManager pm = PMF.getPMFactory().getPersistenceManager();
		try{
			pm.makePersistent(item);
		}finally{
			pm.close();
		}
		
		String query = "select from " + Item.class.getName() + " order by createTime desc";
		pm = PMF.getPMFactory().getPersistenceManager();
	    List<Item> items = (List<Item>) pm.newQuery(query).execute();
	    for(Item i:items){
	    	System.out.println("title:"+i.getTitle());
	    }
	    pm.close();
	}
}
